package cn.dansj.bean;

import cn.dansj.common.utils.bean.CacheToken;
import cn.dansj.common.utils.bean.RequestToken;
import cn.dansj.common.utils.transfer.Verification;
import cn.dansj.entity.User;
import cn.dansj.common.utils.transfer.DefaultMethods;
import cn.dansj.common.utils.transfer.Transformation;
import cn.dansj.utils.project.ProjectUtils;

public class CurrentThreadLocalUserInfo {
    private static final InheritableThreadLocal<ThreadLocalUserInfo> currentThreadLocalUserInfo = new InheritableThreadLocal<>();

    public static void setCurrentThreadLocalUserInfo() {
        currentThreadLocalUserInfo.set(new ThreadLocalUserInfo());
    }

    public static void removeCurrentThreadLocalUserInfo() {
        currentThreadLocalUserInfo.remove();
    }

    public static ThreadLocalUserInfo getCurrentThreadLocalUserInfo() {
        if (currentThreadLocalUserInfo.get() == null) setCurrentThreadLocalUserInfo();
        return currentThreadLocalUserInfo.get();
    }

    public static boolean islogin() {
        return Verification.checkNotNull(getCurrentThreadLocalUserInfo().cacheToken.getSequence());
    }

    public static class ThreadLocalUserInfo extends DefaultMethods {
        private final RequestToken requestToken;
        private final CacheToken cacheToken;
        private final User tokenUser;
        private final CurrentUser currentUser;

        private ThreadLocalUserInfo() {
            this.requestToken = Transformation.lambdaTryCatch(ProjectUtils::parseRequestToken, () -> null);
            this.cacheToken = ProjectUtils.getCacheToken();
            this.tokenUser = ProjectUtils.getUserInterfaceTokenInfo();
            CurrentUser currentUser = new CurrentUser();
            currentUser.setSequence(Transformation.nvl(cacheToken.getSequence(), tokenUser.getSequence()));
            currentUser.setUsername(Transformation.nvl(cacheToken.getUsername(), tokenUser.getUsername()));
            currentUser.setRole(Transformation.nvl(cacheToken.getRole(), tokenUser.getRole()));
            currentUser.setToken(Transformation.nvl(cacheToken.getApiToken(), tokenUser.getToken()));
            this.currentUser = currentUser;
        }

        public CacheToken getCacheToken() {
            return cacheToken;
        }

        public User getTokenUser() {
            return tokenUser;
        }

        public CurrentUser getCurrentUser() {
            return currentUser;
        }

        public RequestToken getRequestToken() {
            return requestToken;
        }
    }
}
